package com.mlnx.netty.handler;


import com.mlnx.bptp.BpPacket;
import com.mlnx.bptp.util.TurnByte;
import com.mlnx.common.utils.MyLog;
import com.mlnx.device.util.CmdUtils;
import com.mlnx.netty.base.handler.BaseSimpleChannelInboundHandler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.shan.mq.session.core.Session;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by amanda.shan on 2019/4/1.
 */
public class SessionCheckHandler extends BaseSimpleChannelInboundHandler<BpPacket> {

    private MyLog log = MyLog.getLog(this.getClass());

    private Timer checkSessionTimer = new Timer();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("连接上" + ctx.channel());
        checkSessionTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (ctx.channel().isActive()) {
                    Session session = sessionManager.getSession(ctx.channel());
                    if (session==null) {
                        log.info("设备未注册,询问设备ID");
                        ctx.writeAndFlush(Unpooled.copiedBuffer(CmdUtils.askDeviceId));
                    } else {
                        ctx.writeAndFlush(Unpooled.copiedBuffer(CmdUtils.electricCrc));
                        log.info("询问电量："+ TurnByte.bytesToHex(CmdUtils.electricCrc));
                        checkSessionTimer.cancel();
                    }
                } else {
                    checkSessionTimer.cancel();
                }
            }
        }, 0,5000);

    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("断开连接" + ctx.channel());
        checkSessionTimer.cancel();
        sessionManager.removeSession(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BpPacket bpPacket) throws Exception {

        Session session = sessionManager.getSession(ctx.channel());
        if(session!=null){
            session.setLastPacketTime(new Date());
        }
        ctx.fireChannelRead(bpPacket);
    }
}
